package agile.hustler.activities;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import agile.hustler.activities.R;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ComSetup extends Activity {

	EditText IPadressField;
	TextView connectionStatusField,recieveStatusField;
	public static InetAddress hostAddress, clientAdress;
	public static DatagramSocket serverSocket, clientSocket;
	public static final int HOST_PORT = 13371;
	public static int clientPort;
	
	Toast toasthelp;
	TextView text;
	Typeface face;
	static String IPconnection;
	String data;
	Bundle b;
	DatagramPacket packet;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		face=Typeface.createFromAsset(getAssets(), "fonts/SEVERINA.ttf");
	    Typeface face2=Typeface.createFromAsset(getAssets(), "fonts/Comic Book.ttf");
		
		toasthelp = Toast.makeText(this, "", 90000000);   
		
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast2,(ViewGroup) findViewById(R.id.toast2));
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifimenu);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		b = getIntent().getExtras();
		data = b.getString("key");
		IPadressField = (EditText) findViewById(R.id.EditText_IPconnection);
		connectionStatusField = (TextView) findViewById(R.id.TextView_HostStatus);
		try {
			hostAddress = InetAddress.getByName(getLocalIpAddress());
			connectionStatusField.setText("Host address: " + hostAddress);
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
		}
		
		findViewById(R.id.ButtonBack).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View v) {
						
						Bundle B = new Bundle();

						B.putString("key", data);

						Intent intent = new Intent(ComSetup.this,
								CharacterScreen.class);

						intent.putExtras(B);

						startActivity(intent);
						
						finish();
						System.gc();
					}
				});
		

	    text = (TextView) layout.findViewById(R.id.text);
	    text.setTypeface(face2);
		toasthelp.setView(layout);
		
		
		findViewById(R.id.Help).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View v) {
						text.setText("If you want to start a wifi game, press 'Start Host' and tell your buddy your ip number. " +
								"He/she will then enter it and press 'Connect to'. \n \n If you instead want to fight a random generated Bot, choose 'Fight Bot'.");
						toasthelp.setGravity(Gravity.TOP|Gravity.LEFT, 0, 140); 
						toasthelp.show();		
						
					}
				});
		
	}

	public void startHost(View view){
		try {
			serverSocket = new DatagramSocket(HOST_PORT, hostAddress);

		} catch (SocketException e) {
			
			e.printStackTrace();
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
		connectionStatusField.setTypeface(face);
		connectionStatusField.setText("Host started on: " + hostAddress);
		byte[] buf = new byte[100];
		packet = new DatagramPacket(buf, buf.length);
		try {
			serverSocket.setSoTimeout(10000);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			serverSocket.receive(packet);
			clientAdress = packet.getAddress();
			clientPort = packet.getPort();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// send character
		byte[] buf0 = b.getString("key").getBytes();
		DatagramPacket packet0 = new DatagramPacket(buf0, buf0.length,
				clientAdress, clientPort);
		try {
			serverSocket.send(packet0);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//Bundle B = new Bundle();
		b.putString("key", data);
		b.putString("key2", new String(packet.getData()));
		Intent intent = new Intent(ComSetup.this,
				FightSplashHost.class);

		intent.putExtras(b);

		startActivity(intent);
		finish();
		System.gc();
	}

	public void connectToHost(View view) {
		try {
			clientSocket = new DatagramSocket();
		} catch (SocketException e1) {
			
			e1.printStackTrace();
		}
		IPconnection = IPadressField.getText().toString();
		InetAddress hostAddress = null;
		try {
			hostAddress = InetAddress.getByName(IPconnection);
		} catch (UnknownHostException e1) {
			
			e1.printStackTrace();
		}
		
		// send character
		byte[] buf = b.getString("key").getBytes();
		DatagramPacket packet = new DatagramPacket(buf, buf.length,
				hostAddress, HOST_PORT);
		try {
			clientSocket.send(packet);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		// recieve other character
		byte[] buf2 = new byte[100];
		//byte[] buf3 = new byte[1000];
		DatagramPacket rcvPacket = new DatagramPacket(buf2, buf2.length);
		//DatagramPacket logPacket = new DatagramPacket(buf3, buf3.length);
		try {
			clientSocket.setSoTimeout(10000);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			clientSocket.receive(rcvPacket);
			//clientSocket.receive(logPacket);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// TODO show log;
		b.putString("key", data);
		b.putString("key2", new String(rcvPacket.getData()).trim());
		//b.putString("log", new String(logPacket.getData()));
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Intent intent = new Intent(ComSetup.this,
		FightSplashClient.class);

		intent.putExtras(b);

		startActivity(intent);
		finish();
		System.gc();
		
	}

	public void recieveData(View view) {
		byte[] buf = new byte[100];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		try {
			serverSocket.receive(packet);
			clientAdress = packet.getAddress();
			clientPort = packet.getPort();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	
		
		
		b.putString("key", data);
		b.putString("key2", new String(packet.getData()));
		Intent intent = new Intent(ComSetup.this,
				FightSplashHost.class);

		intent.putExtras(b);

		startActivity(intent);
		finish();
		System.gc();
		
	}
	
	
	
	
	public void fightBot(View view){
		//Bundle B = new Bundle();
		b.putString("key", data);
		double randomVal = Math.random();
		int r = 0;
		if(randomVal < 0.33) r = 1;
		if(randomVal >= 0.33 && randomVal < 0.66) r = 2;
		if(randomVal >= 0.66) r = 3;
		 //(int)(1+Math.random()*2);
		b.putInt("key2", r);
		Intent intent = new Intent(ComSetup.this,
				FightSplashBot.class);

		intent.putExtras(b);

		startActivity(intent);
		finish();
		System.gc();
	}

	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			// Log.e(LOG_TAG, ex.toString());
		}
		return null;
	}
	
	
	
}
